<?php

namespace app\company\controller\report;

use app\common\controller\CompanyController;
use app\common\enum\order\OrderType;
use app\common\enum\order\PayeeType;
use app\common\enum\order\ReasonType;
use app\common\enum\order\ReceiveType;
use app\common\model\Dealer;
use app\common\model\ReceiveLog;
use app\common\model\Salesman;
use app\common\model\SalesmanDealer;
use app\common\service\annotation\ControllerAnnotation;
use app\company\model\CompanyOrder;
use app\company\model\Payment;
use think\App;
use think\response\Json;
use app\common\model\DealerGoodsSpec;
use app\common\model\Store;
use jianyan\excel\Excel;

/**
 * @ControllerAnnotation(title="销售报表")
 */
class Sale extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * @NodeAnnotation(title="销售报表 业务员订单统计 ")
     */
    public function salesman()
    {
        $param = $this->request->get();
        $where = [];
        $filter = [];
        if (isset($param['filter'])) {
            $filter = json_decode($param['filter'], true);
        }
        if (!empty($filter['salesman_name'])) {
            $where[] = ['rename', 'like', '%' . $filter['salesman_name'] . '%'];
        }
        if (!empty($filter['salesman_id'])) {
            $where[] = ['id', '=', $filter['salesman_id']];
        }


        // print_r( $where);
        $salesmanModel = new Salesman();

        $sql = $salesmanModel->field('id,rename')->where($this->defaultWhere)->where($where);
        if (isset($param['export'])  && $param['export']  == true) {
            $list =  $sql->select()->toArray();
            $list =  $this->fordata_salesman($list, $filter);
        } else {
            $list =  $sql->paginate($param['limit'] ?? 15)->toArray();
            $list['data'] =  $this->fordata_salesman($list['data'], $filter);

            //合计
            $all_data = $sql->select()->toArray();
            $all_data =  $this->fordata_salesman($all_data, $filter);
            $list['order_money'] = array_sum(array_column($all_data, 'order_money'));
            $list['order_count'] = array_sum(array_column($all_data, 'order_count'));
            $list['sk'] = array_sum(array_column($all_data, 'sk'));
            $list['qk'] = array_sum(array_column($all_data, 'qk'));
            $list['zqds'] = array_sum(array_column($all_data, 'zqds'));
            $list['zqss'] = array_sum(array_column($all_data, 'zqss'));
            $list['ycsk'] = array_sum(array_column($all_data, 'ycsk'));
            $list['yczc'] = array_sum(array_column($all_data, 'yczc'));
        }


        if (isset($param['export'])  && $param['export']  == true) {
            $header = [
                ['业务员', 'rename'],
                ['订单金额', 'order_money'],
                ['订单数量', 'order_count'],
                ['订单收款', 'sk'],
                ['订单欠款', 'qk'],
                ['账期金额', 'zq'],
                ['账期待收', 'zqds'],
                ['账期实收', 'zqss'],
                ['预存收款', 'ycsk'],
                ['预存支出', 'yczc']
            ];
            $fileName = '业务员订单统计报表';
            return Excel::exportData($list, $header, $fileName, 'xlsx');
        } else {
            return $this->success($list);
        }
    }
    public function fordata_salesman($list, $filter)
    {
        $orderModel = new CompanyOrder();
        $paymentModel = new Payment();
        $receiveModel = new ReceiveLog();
        foreach ($list as $k => &$item) {
            $orderWhere = [
                ['salesman_id', '=', $item['id']],
                ['pid', '<>', 0],
                ['order_type', '=', OrderType::SALES],
            ];
            $paymentWhere = [
                ['payee_type', '=', PayeeType::SALESMAN],
                ['payee_id', '=', $item['id']],
            ];
            //按照时间搜索
            if (isset($filter['create_time'])) {
                $create_time = $filter['create_time'];
                $start_time = strtotime($create_time[0]);
                $end_time = strtotime('+1 day -1 second',  strtotime($create_time[1]));
                $orderWhere[] = ['create_time', 'between', [$start_time, $end_time]];
                $paymentWhere[] = ['create_time', 'between', [$start_time, $end_time]];
            }
            // 订单金额
            $item['order_money'] = $orderModel->where($orderWhere)->sum('order_amount');
            // 订单数
            $item['order_count'] = $orderModel->where($orderWhere)->count();
            // 收款
            $item['sk'] = $orderModel->where($orderWhere)->sum('pay_amount');
            // 欠款
            $item['qk'] = $orderModel->where($orderWhere)->sum('unsay_amount');
            // 账期总额
            $item['zq'] = $orderModel->where($orderWhere)->where('receive_type', ReceiveType::ZQ)->sum('order_amount');
            // 账期待收
            $item['zqds'] = $paymentModel->where($paymentWhere)->where('pay_status', Payment::WAIT)->sum('money');
            // 账期实收
            $item['zqss'] = $paymentModel->where($paymentWhere)->where('pay_status', Payment::SUCCESS)->sum('money');
            // 预存收款
            $item['ycsk'] = $receiveModel->where($paymentWhere)->where('reason', ReasonType::YC)->sum('money');
            // 预存支出
            $item['yczc'] = $orderModel->where($orderWhere)->where('receive_type', ReceiveType::YC)->sum('order_amount');
        };
        return $list;
    }
    /**
     * @NodeAnnotation(title="销售报表 经销商订单统计 ")
     */
    public function dealer()
    {
        $param = $this->request->get();
        $where = [];
        $filter = [];
        if (isset($param['filter'])) {
            $filter = json_decode($param['filter'], true);
        }
        if (!empty($filter['dealer_name'])) {
            $where[] = ['name', 'like', '%' . $filter['dealer_name'] . '%'];
        }
        if (!empty($filter['dealer_id'])) {
            $where[] = ['id', '=', $filter['dealer_id']];
        }
        //按照时间搜索
        if (isset($filter['create_time'])) {
            $create_time = $filter['create_time'];
            $start_time = strtotime($create_time[0]);
            $end_time = strtotime('+1 day -1 second',  strtotime($create_time[1]));
            $where[] = ['create_time', 'between', [$start_time, $end_time]];
        }
        $dealerModel = new Dealer();

        $sql = $dealerModel->field('id,name')->where($this->defaultWhere)->where($where);
        if (isset($param['export'])  && $param['export']  == true) {
            $list = $sql->select()->toArray();
            $list =  $this->fordata_dealer($list, $filter);
        } else {
            $list = $sql->paginate($post['limit'] ?? 15)->toArray();
            $list['data'] = $this->fordata_dealer($list['data'], $filter);

            //合计
            $all_data = $sql->select()->toArray();
            $all_data =  $this->fordata_dealer($all_data, $filter);
            $list['order_money'] = array_sum(array_column($all_data, 'order_money'));
            $list['order_count'] = array_sum(array_column($all_data, 'order_count'));
            $list['sk'] = array_sum(array_column($all_data, 'sk'));
            $list['qk'] = array_sum(array_column($all_data, 'qk'));
            $list['zqds'] = array_sum(array_column($all_data, 'zqds'));
            $list['zqss'] = array_sum(array_column($all_data, 'zqss'));
            $list['ycsk'] = array_sum(array_column($all_data, 'ycsk'));
            $list['yczc'] = array_sum(array_column($all_data, 'yczc'));
        }

        if (isset($param['export'])  && $param['export']  == true) {
            $header = [
                ['经销商', 'name'],
                ['订单金额', 'order_money'],
                ['订单数量', 'order_count'],
                ['订单收款', 'sk'],
                ['订单欠款', 'qk'],
                ['账期金额', 'zq'],
                ['账期待收', 'zqds'],
                ['账期实收', 'zqss'],
                ['预存收款', 'ycsk'],
                ['预存支出', 'yczc']
            ];


            $fileName = '经销商订单统计报表';
            return Excel::exportData($list, $header, $fileName, 'xlsx');
        } else {
            return $this->success($list);
        }
    }
    public function fordata_dealer($list, $filter)
    {
        $salesmanDealerModel = new SalesmanDealer();
        $orderModel = new CompanyOrder();
        $paymentModel = new Payment();
        $receiveModel = new ReceiveLog();
        foreach ($list as $k => &$item) {
            $orderWhere = [
                ['dealer_id', '=', $item['id']],
                ['pid', '<>', 0],
                ['order_type', '=', OrderType::SALES],
            ];
        
            // 查询业务员ID数组
            $salesmanIds = $salesmanDealerModel->where('dealer_id', $item['id'])->where($this->defaultWhere)->column('salesman_id');
            $paymentWhere = [
                ['payee_type', '=', PayeeType::SALESMAN],
                ['payee_id', 'in', $salesmanIds],
            ];
                //按照时间搜索
                if (isset($filter['create_time'])) {
                    $create_time = $filter['create_time'];
                    $start_time = strtotime($create_time[0]);
                    $end_time = strtotime('+1 day -1 second',  strtotime($create_time[1]));
                    $orderWhere[] = ['create_time', 'between', [$start_time, $end_time]];
                    $paymentWhere[] = ['create_time', 'between', [$start_time, $end_time]];
                }
            // 订单金额
            $item['order_money'] = $orderModel->where($orderWhere)->sum('order_amount');
            // 订单数
            $item['order_count'] = $orderModel->where($orderWhere)->count();
            // 收款
            $item['sk'] = $orderModel->where($orderWhere)->sum('pay_amount');
            // 欠款
            $item['qk'] = $orderModel->where($orderWhere)->sum('unsay_amount');
            // 账期总额
            $item['zq'] = $orderModel->where($orderWhere)->where('receive_type', ReceiveType::ZQ)->sum('order_amount');
            // 账期待收
            $item['zqds'] = $paymentModel->where($paymentWhere)->where('pay_status', Payment::WAIT)->sum('money');
            // 账期实收
            $item['zqss'] = $paymentModel->where($paymentWhere)->where('pay_status', Payment::SUCCESS)->sum('money');
            // 预存收款
            $item['ycsk'] = $receiveModel->where($paymentWhere)->where('reason', ReasonType::YC)->sum('money');
            // 预存支出
            $item['yczc'] = $orderModel->where($orderWhere)->where('receive_type', ReceiveType::YC)->sum('order_amount');
        };
        return $list;
    }
    /**
     * @NodeAnnotation(title="销售报表 门店订单统计 ")
     */
    public function store()
    {
        $param = $this->request->get();
        $where = [];
        $filter = [];
        if (isset($param['filter'])) {
            $filter = json_decode($param['filter'], true);
        }
        if (!empty($filter['store_name'])) {
            $store_id = Store::where('name', 'like', '%' . $filter['store_name'] . '%')->column('id');
            $where[] = ['store_id', 'in', $store_id];
        }
        if (!empty($filter['dealer_id'])) {
            $where[] = ['dealer_id', '=', $filter['dealer_id']];
        }
        if (!empty($filter['store_id'])) {
            $where[] = ['store_id', '=', $filter['store_id']];
        }

        // var_dump($where);
        $orderModel = new CompanyOrder();

        $orderWhere = [
            ['pid', '<>', 0],
            ['order_type', '=', OrderType::SALES],
        ];
        $sql = $orderModel->field('id,store_id,dealer_id')
            ->with([
                'store' => function ($query) {
                    $query->field('id,name');
                },
                'dealer' => function ($query) {
                    $query->field('id,name');
                }
            ])
            ->where($orderWhere)->where($this->defaultWhere)->where($where)
            ->group('store_id,dealer_id');
        if (isset($param['export'])  && $param['export']  == true) {
            $sql = $sql->select();
            $list =  $sql->toArray();
            $list =  $this->fordata_store($list, $filter);
        } else {
            $list = $sql->paginate($param['limit'] ?? 15)->toArray();
            $list['data'] =  $this->fordata_store($list['data'], $filter);

            //合计
            $all_data = $sql->select()->toArray();
            $all_data =  $this->fordata_store($all_data, $filter);
            $list['order_money'] = array_sum(array_column($all_data, 'order_money'));
            $list['order_count'] = array_sum(array_column($all_data, 'order_count'));
            $list['sk'] = array_sum(array_column($all_data, 'sk'));
            $list['qk'] = array_sum(array_column($all_data, 'qk'));
            $list['zqds'] = array_sum(array_column($all_data, 'zqds'));
            $list['zqss'] = array_sum(array_column($all_data, 'zqss'));
            $list['ycsk'] = array_sum(array_column($all_data, 'ycsk'));
            $list['yczc'] = array_sum(array_column($all_data, 'yczc'));
        }

        if (isset($param['export'])  && $param['export']  == true) {

            $header = [
                ['门店', 'store.name'],
                ['订单金额', 'order_money'],
                ['订单数量', 'order_count'],
                ['订单收款', 'sk'],
                ['订单欠款', 'qk'],
                ['账期金额', 'zq'],
                ['账期待收', 'zqds'],
                ['账期实收', 'zqss'],
                ['预存收款', 'ycsk'],
                ['预存支出', 'yczc'],
                ['经销商', 'dealer.name']
            ];


            $fileName = '门店订单统计报表';
            return Excel::exportData($list, $header, $fileName, 'xlsx');
        } else {
            return $this->success($list);
        }
    }

    public function fordata_store($list, $filter)
    {
        $paymentModel = new Payment();
        $receiveModel = new ReceiveLog();
        $orderModel = new CompanyOrder();
        foreach ($list as $k => &$item) {
            $orderWhere = [
                ['store_id', '=', $item['store_id']],
                ['dealer_id', '=', $item['dealer_id']],
                ['pid', '<>', 0],
                ['order_type', '=', OrderType::SALES],
            ];

            $paymentWhere = [
                ['store_id', '=', $item['store_id']],
            ];
            //按照时间搜索
            if (isset($filter['create_time'])) {
                $create_time = $filter['create_time'];
                $start_time = strtotime($create_time[0]);
                $end_time = strtotime('+1 day -1 second',  strtotime($create_time[1]));
                $orderWhere[] = ['create_time', 'between', [$start_time, $end_time]];
                $paymentWhere[] = ['create_time', 'between', [$start_time, $end_time]];
            }
            // 订单金额
            $item['order_money'] = $orderModel->where($orderWhere)->sum('order_amount');
            // 订单数
            $item['order_count'] = $orderModel->where($orderWhere)->count();
            // 收款
            $item['sk'] = $orderModel->where($orderWhere)->sum('pay_amount');
            // 欠款
            $item['qk'] = $orderModel->where($orderWhere)->sum('unsay_amount');
            // 账期总额
            $item['zq'] = $orderModel->where($orderWhere)->where('receive_type', ReceiveType::ZQ)->sum('order_amount');
            // 账期待收
            $item['zqds'] = $paymentModel->where($paymentWhere)->where('pay_status', Payment::WAIT)->sum('money');
            // 账期实收
            $item['zqss'] = $paymentModel->where($paymentWhere)->where('pay_status', Payment::SUCCESS)->sum('money');
            // 预存收款
            $item['ycsk'] = $receiveModel->where($paymentWhere)->where('reason', ReasonType::YC)->sum('money');
            // 预存支出
            $item['yczc'] = $orderModel->where($orderWhere)->where('receive_type', ReceiveType::YC)->sum('order_amount');
        };
        return $list;
    }
}
